package ar.com.duam.porky.movil;

import java.net.MalformedURLException;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import ar.com.duam.porky.movil.tasks.DownloadConceptosTask;
import ar.com.duam.porky.movil.tasks.LoginTask;

public class ActivityLogin extends Activity 
{
	private static final int DIALOG_WRONG_CREDENTIALS = 0;
	private ProgressBar progressBarLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_activity_login);
        
        progressBarLogin = (ProgressBar) findViewById(R.id.progressBarLogin);
        
        SharedPreferences prefs = getSharedPreferences(ConstantesPorky.PREFS_NAME, MODE_PRIVATE);
        String username = prefs.getString("username", "-");
        
        EditText nombreUsuario = (EditText) findViewById(R.id.nombreUsuario);
        nombreUsuario.setText(username);
    }

    /** Called when the user clicks the Ingresar button */
    public void ingresar(View view)
    {
    	String username = ((EditText) findViewById(R.id.nombreUsuario)).getText().toString();
    	String password = ((EditText) findViewById(R.id.clave)).getText().toString();

		Syncro syncro = new Syncro();
		
		if (syncro.isNetworkAvailable(getApplicationContext()))
		{
	    	if (login(username, password))
	    	{
	    		Usuario usuario = almacenarUsuario(username, password);
	    		
	    		try 
	    		{
					sincronizarConceptos(this, usuario);
				} 
	    		catch (InterruptedException e) 
	    		{
					e.printStackTrace();
				} 
	    		catch (ExecutionException e) 
	    		{
					e.printStackTrace();
				}
	    		
		    	Intent intent = new Intent(this, ListadoMovimientosActivity.class);
		    	startActivity(intent);
	    	}
	    	else
	    	{
	    		pop("Usuario o contraseña inválidos");
	    	}
		}
		else
		{
			pop("Imposible loguearse sin conexión a Internet");
		}
    }
    
	public void sincronizarConceptos(Context contexto, Usuario usuario) throws InterruptedException, ExecutionException
	{
		PorkyOpenHelper helper = new PorkyOpenHelper(contexto);
		helper.borrarConceptos(usuario);
		
		DownloadConceptosTask task = new DownloadConceptosTask()
		{
			@Override
			protected void onProgressUpdate(Integer... values) 
			{
				progressBarLogin.setProgress(values[0]);
			}			
		};
		task.execute(usuario);
		
		for (Concepto concepto : task.get())
		{
			helper.addConcepto(concepto);
		}
	}
    
    private void pop(String message)
    {
		Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
    }
    
    /**
     * Guardar en las preferencias y en la base.
     * 
     * @param username
     * @param password
     */
    private Usuario almacenarUsuario(String username, String password)
    {
    	Editor editor = getSharedPreferences(ConstantesPorky.PREFS_NAME, MODE_PRIVATE).edit();
    	editor.putString("username", username);    	
    	editor.commit();
	
    	Usuario usuario = new Usuario(1, username, username, password);
    	PorkyOpenHelper helper = new PorkyOpenHelper(this);
    	helper.addUsuario(usuario);
    	
    	return usuario;
    }
    
    @Override
	@Deprecated
	protected Dialog onCreateDialog(int id) 
    {
    	Dialog dialog;
    	
    	switch (id) 
    	{
			case DIALOG_WRONG_CREDENTIALS:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("Usuario o contrase�a incorrectos").setCancelable(false).setNeutralButton("OK", new DialogInterface.OnClickListener() 
				{					
					public void onClick(DialogInterface dialog, int which) 
					{
						dialog.dismiss();
					}
				});
				dialog = builder.create();
				break;
			default:
				dialog = null;
		}
    	
    	return dialog;
	}

    /**
     * Le consulta al sitio porky si es v�lido el login.
     * 
     * @param username
     * @param password
     * @return
     * @throws MalformedURLException 
     */
	private Boolean login(String username, String password)
    {
		LoginTask task = new LoginTask();
		task.execute(username, password);
		
		try 
		{
			return task.get();
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
			return false;
		} 
		catch (ExecutionException e) 
		{
			e.printStackTrace();
			return false;
		}
    }
    
	public static boolean isInternetConnectionActive(Context context) 
	{
		NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

		return !(networkInfo == null || !networkInfo.isConnected()); 
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        getMenuInflater().inflate(R.menu.activity_activity_login, menu);
        return true;
    }
    
}
